package com.yancy.controller;

import com.google.gson.Gson;
import com.yancy.entity.User;
import com.yancy.service.UserService;
import com.yancy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @description:
 * @author: YancyZhang
 * @time: 2021/11/27 10:58
 */
@WebServlet("/adminUser")
public class AdminUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("delete")){
            UserService userService = new UserServiceImpl();
            PrintWriter out = resp.getWriter();
            out.print(userService.deleteUser(req.getParameter("id")));
        } else if(method.equals("add")){
            UserService userService = new UserServiceImpl();
            PrintWriter out = resp.getWriter();
            out.print(userService.addUser(req));
        } else if(method.equals("update")){
            UserService userService = new UserServiceImpl();
            PrintWriter out = resp.getWriter();
            out.print(userService.updateUser(req));
        } else if(method.equals("select")){
            UserService userService = new UserServiceImpl();
            List<User> list = userService.getUser();
            Gson gson = new Gson();
            String json = gson.toJson(list);
            PrintWriter out = resp.getWriter();
            out.print(json);
        } else {
            PrintWriter out = resp.getWriter();
            out.print(false);
        }
    }
}